package com.template.common.aspect;

import com.template.common.annotation.CacheRemove;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class CacheRemoveAspect {

    private final RedisTemplate<String, Object> redisTemplate;

    @AfterReturning("@annotation(com.template.common.annotation.CacheRemove)")
    public void remove(JoinPoint point) {
        Method method = ((MethodSignature) point.getSignature()).getMethod();

        CacheRemove cacheRemove = method.getAnnotation(CacheRemove.class);
        Set<String> deleteKeys = new HashSet<>();
        for (String key : cacheRemove.value()) {
            if (key.contains("#"))
                key = parseKey(key, method, point.getArgs());

            Set<String> keys = redisTemplate.keys(key);
            if (keys != null) deleteKeys.addAll(keys);
        }
        if (deleteKeys.size() != 0) redisTemplate.delete(deleteKeys);
        log.info("cache key: " + deleteKeys + " deleted");
    }


    /**
     * parseKey from SPEL
     */
    private String parseKey(String key, Method method, Object[] args) {
        StandardReflectionParameterNameDiscoverer u = new StandardReflectionParameterNameDiscoverer();
        String[] paraNameArr = u.getParameterNames(method);

        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();

        for (int i = 0; paraNameArr != null && i < paraNameArr.length; i++) {
            context.setVariable(paraNameArr[i], args[i]);
        }
        return parser.parseExpression(key).getValue(context, String.class);
    }
}
